const api = require("../../utils/api.js");
const tools = require("../../utils/getuserinfo.js");
const utils = require("../../utils/utils.js");
const internal = require("../../utils/international.js");
const app = getApp();
const config = app.siteInfo;
const util = app.util;

app.modules = "ws_micro_shop";
let int = null;
let interval = null;
let page_first_init = true;
let timer = null;
let msgHistory = "";

const WxNotificationCenter = require("../../../common/utils/WxNotificationCenter/WxNotificationCenter");
WxNotificationCenter.postNotificationName(app.INJECT_BLOBAL_EVENT, {
  global: require("../../global"),
  module: "ws_micro_shop",
});

Page({
  data: {
    x: wx.systemInfo.windowWidth,
    y: wx.systemInfo.windowHeight,
    left: 0,
    show_notice: false,
    animationData: {},
    play: -1,
    noScrollListen: false,
    time: 0,
    buy_user: "",
    buy_address: "",
    buy_time: 0,
    leng:
      app.siteInfo && app.siteInfo.appJson ? app.siteInfo.appJson.length : 0,
    currentInde: 0,
    tabbarindex: app.tabbarindex,
    attachment_url: app.siteInfo.attachment_url,
    domain: app.siteInfo.domain,
    finished: false,
    duration: 1,
    unit: "",
    form: {
      number: 1,
    },
    show_attr_picker: false,
    showQRcode: false,
    QRcodeUrl: "",
    quickCat: true,
    useTabbar: !(app.tabbarindex === 0 && app.siteInfo.tabbar_type === "1"),
    more: true,
    page: 2,
    isGuideCoupon: false,
    swiperCurrent: 0,
    is_show_line: false,
    imgUrl: app.imgUrl,
    isSingle: app.ws_micro_shop_globalData.isSingle,
    isPlatShow: internal.getOrderStatus("isPlatShow"),
    template_type: app.ws_micro_shop_globalData.template_type,
    version_type: app.ws_micro_shop_globalData.version_type,
    isLoad: false,
    bg: config.appJson[0].window.navigationBarBackgroundColor,
    textColor: config.appJson[0].window.navigationBarTextStyle,
  },
  onLoad(opts) {
    let that = this;
    let options = opts || {};
    let parent_id = 0;
    let shop_id = 0;
    let share_scene = "";
    let user_id = options.user_id;
    let scene = decodeURIComponent(options.scene);
    if (options && options.shopid) {
      app.ws_micro_shop_globalData.shopid = options.shopid;
      shop_id = options.shopid;
    }
    app.ws_micro_shop_globalData.fromHome = false; // 在门店首页底部菜单肯定不是平台首页
    // 截流应用
    let queryParam = decodeURIComponent(options.q);
    if (queryParam !== "undefined") {
      that.setData({
        queryParam: queryParam,
        showClosure: true,
      });
    }
    app.getSystemInfo();
    app.tabbarindex = options.tabbarindex
      ? options.tabbarindex - 0
      : app.tabbarindex;

    if (typeof user_id !== "undefined") {
      parent_id = user_id;
      share_scene = 4;
    } else if (scene && scene !== "undefined") {
      if (scene.indexOf("=") > 0) {
        let scene_obj = scene.split("&");
        let urlObj = {};
        for (let i = 0; i < scene_obj.length; i++) {
          urlObj[scene_obj[i].split("=")[0]] = scene_obj[i].split("=")[1];
        }
        if (urlObj.sp) {
          shop_id = urlObj.sp;
          app.ws_micro_shop_globalData.shopid = urlObj.sp;
          options.shopid = urlObj.sp;
        }
        urlObj.g_id && (options.guide_id = urlObj.g_id);
      } else {
        let scene_obj = scene.split(",");
        parent_id = scene_obj[0];
        shop_id = scene_obj[1];
        app.ws_micro_shop_globalData.shopid = scene_obj[1];
        if (scene.indexOf(":") > 0 && scene.indexOf(",") > 0) {
          let { gid, sid, g_id } = utils.scene_decode(scene);
          if (g_id && gid) {
            app.ws_micro_shop_globalData.shopid = sid;
            options.id = gid;
            options.guide_id = g_id;
            options.shopid = sid;
            shop_id = sid;
          }
        }
      }
    }
    parent_id && (app.ws_micro_shop_globalData.parent_id = parent_id);
    let sessionFormStr = {
      shop_id: app.ws_micro_shop_globalData.shopid,
    };
    let serviceMessageTitle = "";
    let serviceMessagePath = "index";

    const { navBarHeight, navBarExtendHeight } = app.globalSystemInfo;

    that.setData({
      currentInde: options.tabbarindex
        ? options.tabbarindex - 0
        : app.tabbarindex,
      popovernum: (navBarHeight + navBarExtendHeight) * 2,
      parent_id,
      shop_id,
      share_scene,
      opts: options,
      sessionFormStr: JSON.stringify(sessionFormStr),
      serviceMessageTitle,
      serviceMessagePath,
      useTabbar: that.data.useTabbar && app.getTabBarStatus(),
    });

    that.getInfo();

    app.loadCurrencyUnit().then((res) => {
      that.setData({
        unit: res.unit,
      });
    });

    app.pageOnLoad(this);
  },
  onShow() {
    let is_on_show = wx.getStorageSync("is_on_show");
    if (is_on_show && config.tabbar_type == "1") {
      this.setData({
        isLoad: false,
      });
      this.getInfo();
      wx.removeStorageSync("is_on_show");
    }
  },

  getInfo() {
    wx.showLoading({
      title: "加载中",
      mask: true,
    });
    // app.ws_micro_shop_globalData.loginNum === 0 && wx.hideTabBar();//对原生tabbar的处理 by zlh
    int && clearInterval(int);
    let that = this;
    let { opts, isSingle } = that.data;

    app.ws_micro_shoplogin().then((res) => {

      if (isSingle) {
        that.init();
      } else {
        let userLocation = wx.getStorageSync("userLocation");
        if (userLocation) {
          that.init(userLocation);
          app.getSetting();
        } else {
          app.getSetting().then((res) => {
            that.init(res);
          });
        }
      }

      // let userinfo = wx.getStorageSync('user_info');
      // if (Number(userinfo.info) === 0) {
      //   tools.onGetInfo(that, userinfo.auth_mode);
      // }
      app.util.prepareBindInfo(opts, app.modules, that);
      app.bindGuide(opts);
      app.bindCard2(opts);
    });
  },

  init(loca = {}) {

    let that = this;
    let { time, parent_id, shop_id, share_scene, opts, useTabbar } = that.data;
    app.getStoreData(loca).then((res) => {
      let store = res.store;
      that.data.store = store;

      Number(app.ws_micro_shop_globalData.shopid) ||
        (app.ws_micro_shop_globalData.shopid = res.store.shop_id);
      let { isMulti, isBrand } = app.ws_micro_shop_globalData;
      (isMulti || isBrand) &&
        Number(app.ws_micro_shop_globalData.shopid) === 0 &&
        wx.showModal({
          title: "提示",
          content: "未找到门店信息",
          showCancel: false,
          success(res) {
            if (res.confirm) {
              app.util.navigateTo("/ws_micro_shop/pages/shop/shop", {}, true);
            }
          },
        });

      !useTabbar && wx.showTabBar();
      // let store = wx.getStorageSync("store");

      // Number(shop_id) && (app.ws_micro_shop_globalData.shopid = shop_id);

      // that.setData({
      //   store,
      // });
      if (store && store.purchase_frame === 1) {
        that.suspension(time);
      } else {
        that.setData({
          buy_user: "",
        });
      }

      app.loadShopSetting().then((res) => {

        that.setData({
          settle_model: store.settle_model,
          show_cart: store.show_cart,
          is_coupon: store.is_coupon,
          store_name: res.store_name,
        });
        // that.setData(res);

        that.data = Object.assign(that.data, res);
      })
      .then(() => {
        that.getFloatIcon();
      });

      that.loadData();
      opts.id && that.getCoupon(opts);
      app.resetPurchasedNum();
      app.loginBindParent({
        parent_id,
        shop_id: app.ws_micro_shop_globalData.shopid,
        share_scene,
      });
      that.notice();
    });
  },
  getCoupon(options) {
    app.getCoupon(options, this);
  },
  getGuideCoupon() {
    app.getGuideCoupon(this.data.opts.id, this);
  },
  guideCouponClose() {
    this.setData({
      isGuideCoupon: false,
    });
  },
  suspension(time) {
    let that = this;
    interval = setInterval(function () {
      app.ws_micro_shoprequest({
        url: api.default.buy_data,
        data: {
          time,
        },
        method: "POST",
        success: function (res) {
          if (res.code === 0) {
            let inArray = false;
            if (msgHistory === res.md5) {
              inArray = true;
            }
            let cha_time = "";
            let s = res.cha_time;
            let m = Math.floor(s / 60 - Math.floor(s / 3600) * 60);
            if (m === 0) {
              cha_time = (s % 60) + "秒";
            } else {
              cha_time = m + "分" + (s % 60) + "秒";
            }
            if (!inArray && res.cha_time <= 300) {
              that.setData({
                buy_time: cha_time,
                buy_user:
                  res.data.user.length >= 5
                    ? res.data.user.slice(0, 4) + "..."
                    : res.data.user,
                buy_avatar_url: res.data.avatar_url,
                buy_address:
                  res.data.address.length >= 8
                    ? res.data.address.slice(0, 7) + "..."
                    : res.data.address,
              });
              msgHistory = res.md5;
            } else {
              that.setData({
                buy_user: "",
                buy_address: "",
                buy_avatar_url: "",
                buy_time: "",
              });
            }
          }
        },
      });
    }, 5000);
  },
  loadData() {
    let that = this;
    let { get_coupon_list } = that.data;
    app.ws_micro_shoprequest({
      url: api.default.index_new,
      data: {
        type: "module_list",
      },
      success: function (res) {
        if (res.code === 0) {
          let { nav_count } = res.data;
          nav_count && that.setData({ nav_count });

          app.ws_micro_shop_globalData.orgPrice =
            res.data.show_original_price && res.data.show_original_price == 1
              ? 1
              : 0;
          // that.setData({
          //   orgPrice: app.ws_micro_shop_globalData.orgPrice,
          // });
          let indexData = res.data;
          let module_list_arr = [];
          let module_list_arr2 = [];
          if (
            get_coupon_list &&
            get_coupon_list.length &&
            get_coupon_list.length > 0
          ) {
          } else {
            indexData.get_coupon_list = indexData.new_coupon_list;
          }
          if (!page_first_init) {
            indexData.act_modal_list = [];
            indexData.get_coupon_list = [];
          } else {
            page_first_init = false;
          }

          indexData.module_list.forEach(function (item, index, arr) {
            module_list_arr.push(item.name);
          });
          // that.setData({
          //   isSearchShow: module_list_arr.includes("search"),
          // });
          module_list_arr.forEach(function (item) {
            !module_list_arr2.includes(item) && module_list_arr2.push(item);
          });
          for (let k in module_list_arr2) {
            try {
              that.loadModuleData(module_list_arr2[k]);
            } catch (error) {
              console.log(error);
            }
          }
          // indexData.isLoad = true;
          indexData.orgPrice = app.ws_micro_shop_globalData.orgPrice;
          that.setData(indexData);
          // let _user_info = wx.getStorageSync("user_info");
          // if (_user_info) {
          //   that.setData({
          //     _user_info,
          //     finished: true,
          //   });
          // }
        }
      },
      complete: function () {
        wx.stopPullDownRefresh();
      },
    });
  },
  loadModuleData(name) {
    let that = this;
    app.ws_micro_shoprequest({
      url: api.default.index_new,
      data: {
        type: name,
      },
      success: function (res) {
        if (res.code === 0) {
          let moduleData = res.data;
          if (name === "banner") {
            let bannerList = moduleData.banner_list;
            app.wxAppParams(bannerList, "page_url");
          } else if (name === "nav") {
            let navIconList = moduleData.nav_icon_list;
            app.wxAppParams(navIconList, "url");
            // 处理导航菜单样式
            let navPerGroup = Number(that.data.nav_count) === 1 ? 5 : 4;
            let groupCount = Math.ceil(navIconList.length / navPerGroup);
            let navArray = Array.from({ length: groupCount }, (v, i) =>
              navIconList.slice(i * navPerGroup, i * navPerGroup + navPerGroup)
            );
            that.setData({
              navArray,
            });
          } else if (name === "block") {
            let blockList = moduleData.block_list;
            if (blockList.length > 0) {
              for (let i in blockList) {
                if (Object.prototype.hasOwnProperty.call(blockList, i)) {
                  let magicList = blockList[i].data.pic_list;
                  app.wxAppParams(magicList, "url");
                }
              }
            }
          } else if (name === "miaosha") {
            // 兼容秒杀自定义时间段 如果返回的商品里有一个有 custom_time 属性 则就是自定义时间段
            let goods = res.data.miaosha.goods_list || [];
            let isCustom = goods.some((item) => {
              return (
                item.hasOwnProperty("custom_time") && item.custom_time != ""
              );
            });

            that.setData({ miaosha: res.data.miaosha, isCustom }, () => {
              that.miaoshaTimer();
            });
          } else if (name === "notice") {
            let leng = moduleData.notice ? moduleData.notice.length : "";
            let duration = Math.ceil(leng / 50);
            that.setData({
              duration,
            });
          } else if (name === "pintuan") {
            let list = res.data.pintuan.goods_list;
            let count = Math.ceil(list.length / 3);
            let ptArray;
            if (Number(res.data.pintuan.style) === 0) {
              ptArray = Array.from({ length: count }, (v, i) =>
                list.slice(i * 3, i * 3 + 3)
              );
            }
            that.setData({ ptArray: ptArray ? ptArray : list });
          }
          that.setData(moduleData);
        } else {
          wx.showToast({
            title: res.msg || "",
            icon: "none",
          });
        }
      },
      complete: function () {},
    });
  },
  onPullDownRefresh() {
    timer && clearInterval(timer);
    this.setData({
      page: 2,
      more: true,
      is_show_line: false,
    });
    this.getInfo();
  },
  onShareAppMessage() {
    let that = this;
    let user_info = wx.getStorageSync("user_info");
    let store = that.data.store;
    app.shareSendCoupon(that);
    return {
      path:
        "/ws_micro_shop/pages/index/index?user_id=" +
        user_info.id +
        "&tabbarindex=" +
        app.tabbarindex +
        "&shopid=" +
        app.ws_micro_shop_globalData.shopid,
      title: store.share_index_title
        ? store.share_index_title
        : that.data.store.name,
      desc: store.share_index_desc ? store.share_index_desc : "",
    };
  },
  onShareTimeline() {
    let that = this;
    let user_info = wx.getStorageSync("user_info");
    let store = that.data.store;
    app.shareSendCoupon(that);
    return {
      title: store.share_index_title
        ? store.share_index_title
        : that.data.store.name,
      imageUrl: "",
      query:
        "user_id=" +
        user_info.id +
        "&tabbarindex=" +
        app.tabbarindex +
        "&shopid=" +
        app.ws_micro_shop_globalData.shopid,
    };
  },
  hideGetCoupon(e) {
    let url = e.currentTarget.dataset.url || false;
    this.setData({
      get_coupon_list: null,
      isShowCoupon: false,
    });
    if (url) {
      wx.navigateTo({
        url: url,
      });
    }
  },
  receive(e) {
    let that = this;
    let id = e.currentTarget.dataset.index;
    wx.showLoading({
      title: "领取中",
      mask: true,
    });
    app.access_token(that);
    app.ws_micro_shoprequest({
      url: api.coupon.receive,
      data: {
        id,
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data && res.code === 0) {
          that.setData({
            isShowCoupon: true,
            get_coupon_list: res.data.list,
            coupon_list: res.data.coupon_list,
          });
        } else {
          wx.showToast({
            title: res.msg,
            duration: 2000,
            icon: "none",
          });
          that.setData({
            coupon_list: res.data.coupon_list,
          });
        }
      },
    });
  },
  onNavigate(e) {
    let param = e.currentTarget.dataset;
    let open_type = param.open_type;
    let pageUrl = param.url ? param.url : "";
    if (open_type !== "wxapp") {
      app.ws_micro_shop_navigate(param);
      return;
    } else {
      let url = app.parseQueryString(pageUrl);
      url.path = url.path ? decodeURIComponent(url.path) : "";
      wx.navigateToMiniProgram({
        appId: url.appId,
        path: url.path,
      });
      return false;
    }
  },
  closeCouponBox() {
    this.setData({
      get_coupon_list: "",
      isShowCoupon: false,
    });
  },
  notice() {
    wx.hideLoading();
    this.setData({
      isLoad: true,
    })
    // let notice = this.data.notice;
    // if (typeof notice === "undefined") {
    //   return;
    // }
    // return;
  },
  miaoshaTimer() {
    let that = this;
    let miaoshaData = that.data.miaosha;
    if (!miaoshaData || !miaoshaData.rest_time) {
      return;
    }
    timer && clearInterval(timer);
    timer = setInterval(() => {
      if (miaoshaData.rest_time > 0) {
        miaoshaData.rest_time = miaoshaData.rest_time - 1;
      } else {
        timer && clearInterval(timer);
        // 当前秒杀结束后，立即请求数据，开始下一场秒杀。
        that.loadModuleData("miaosha");
        return;
      }
      miaoshaData.times = that.getTimesBySecond(miaoshaData.rest_time);
      that.setData({
        miaosha: miaoshaData,
      });
    }, 1000);
  },
  onHide() {
    this.setData({
      play: -1,
    });
    // timer && clearInterval(timer);
    int && clearInterval(int);
    interval && clearInterval(interval);
    util.sendBindInfo(this.data);
  },
  onUnload() {
    this.setData({
      play: -1,
    });
    // timer && clearInterval(timer);
    int && clearInterval(int);
    interval && clearInterval(interval);
    util.sendBindInfo(this.data);
  },
  showNotice(e) {
    let type = e.currentTarget.dataset.type;
    if (type === 0) {
      this.setData({
        show_notice: true,
      });
    } else {
      let params = {
        from: "shop",
      };
      app.util.navigateTo("/ws_micro_shop/pages/notice-list/index", params);
    }
  },
  closeNotice() {
    this.setData({
      show_notice: false,
    });
  },
  getTimesBySecond(se) {
    let s = parseInt(se, 10);
    let isCustom = this.data.isCustom;
    if (isNaN(s)) {
      return {
        h: "00",
        m: "00",
        s: "00",
      };
    }
    let _h = parseInt(s / 3600, 10);
    if (_h >= 1 && !isCustom) {
      _h -= 1;
    }
    let _m = parseInt((s % 3600) / 60, 10);
    let _s = s % 60;

    return {
      h: _h < 10 ? "0" + _h : String(_h),
      m: _m < 10 ? "0" + _m : String(_m),
      s: _s < 10 ? "0" + _s : String(_s),
    };
  },
  to_dial() {
    let contact_tel = this.data.contact_tel;
    if (contact_tel !== "" && typeof contact_tel !== "undefined") {
      wx.makePhoneCall({
        phoneNumber: contact_tel,
      });
    } else {
      wx.showToast({
        title: "商家没留手机哦",
        icon: "none",
      });
    }
  },
  closeActModal() {
    let that = this;
    let act_modal_list = that.data.act_modal_list;
    let show_next = true;
    let next_i;
    for (let i in act_modal_list) {
      if (Object.prototype.hasOwnProperty.call(act_modal_list, i)) {
        let index = parseInt(i, 10);
        if (act_modal_list[index].show) {
          act_modal_list[index].show = false;
          next_i = index + 1;
          if (typeof act_modal_list[next_i] !== "undefined" && show_next) {
            show_next = false;
            that.data.act_modal_list[next_i].show = true;
            that.setData({
              act_modal_list: that.data.act_modal_list,
            });
          }
        }
      }
    }
    that.setData({
      act_modal_list: act_modal_list,
    });
  },
  naveClick(e) {
    app.navigatorClick(e, this);
  },
  play(e) {
    this.setData({
      play: e.currentTarget.dataset.index,
    });
  },
  onFullScreen(e) {
    if (e.detail.direction === "horizontal") {
      this.setData({
        noScrollListen: true,
      });
    } else {
      this.setData({
        noScrollListen: false,
      });
    }
  },
  onPageScroll() {
    let that = this;
    if (Number(that.data.play) !== -1 && that.data.noScrollListen === false) {
      wx.createSelectorQuery()
        .select(".video")
        .fields(
          {
            rect: true,
          },
          function (res) {
            let max = wx.systemInfo.windowHeight;
            if (
              res &&
              res.top &&
              res.top !== null &&
              (res.top <= -200 || res.top >= max - 57)
            ) {
              that.setData({
                play: -1,
              });
            }
          }
        )
        .exec();
    }
  },
  collectFormId(e) {
    app.collectFormId(e);
  },
  selectDefaultAttr(use_attr, attr_group_list) {
    let _this = this;
    if (Number(use_attr) !== 0) {
      return;
    }
    for (let i in attr_group_list) {
      if (Object.prototype.hasOwnProperty.call(attr_group_list, i)) {
        for (let j in attr_group_list[i].attr_list) {
          if (Number(i) === 0 && Number(j) === 0) {
            attr_group_list[i].attr_list[j]["checked"] = true;
          }
        }
      }
    }
    _this.setData({
      attr_group_list,
    });
  },
  hideAttrPicker() {
    this.setData({
      show_attr_picker: false,
    });
  },
  disabledClick() {
    // it`s necessary
  },
  showAttrModal(e) {
    let that = this;
    let id = e.currentTarget.dataset.gid;
    let member_only = e.currentTarget.dataset.member_only;
    let userInfo = wx.getStorageSync("user_info");
    if (Number(member_only) === 1 && userInfo && userInfo.level === -1) {
      wx.showModal({
        title: "提示",
        content: "您还不是会员,不能购买此商品",
        showCancel: false,
        success(res) {},
      });
      return false;
    }
    app.ws_micro_shoprequest({
      url: api.default.getattr,
      method: "GET",
      data: {
        id,
      },
      success: function (res) {
        if (res.code === 0) {
          let resp = res.data;
          that.setData({
            goods: resp,
            attr_group_list: resp.attr_group_list,
            // goodsnum: resp.num,
            // goodsunit: resp.unit,
            // goodsprice: resp.price,
            // pic_list: resp.pic_list,
            show_attr_picker: true,
            id,
            "form.number": 1,
          });
          that.selectDefaultAttr(resp.use_attr, resp.attr_group_list);
        }
      },
    });
  },
  numberSub() {
    let num = this.data.form.number;
    if (num <= 1) {
      return true;
    }
    num--;
    this.setData({
      form: {
        number: num,
      },
    });
  },
  numberAdd() {
    let num = this.data.form.number;
    num++;
    this.setData({
      form: {
        number: num,
      },
    });
  },
  numberBlur(e) {
    let num = e.detail.value;
    num = parseInt(num, 10);
    if (isNaN(num)) {
      num = 1;
    }
    if (num <= 0) {
      num = 1;
    }
    this.setData({
      form: {
        number: num,
      },
    });
  },
  addCart() {
    this.submit("ADD_CART");
  },
  buyNow() {
    this.submit("BUY_NOW");
  },
  submit(type) {
    let _this = this;
    if (_this.data.form.number > _this.data.goods.num) {
      wx.showToast({
        title: "商品库存不足，请选择其它规格或数量",
        icon: "none",
      });
      return true;
    }
    let attr_group_list = _this.data.attr_group_list;
    let checked_attr_list = [];
    for (let i in attr_group_list) {
      if (Object.prototype.hasOwnProperty.call(attr_group_list, i)) {
        let attr = false;
        for (let j in attr_group_list[i].attr_list) {
          if (attr_group_list[i].attr_list[j].checked) {
            attr = {
              attr_id: attr_group_list[i].attr_list[j].attr_id,
              attr_name: attr_group_list[i].attr_list[j].attr_name,
            };
            break;
          }
        }
        if (!attr) {
          wx.showToast({
            title: "请选择" + attr_group_list[i].attr_group_name,
            icon: "none",
          });
          return true;
        } else {
          checked_attr_list.push({
            attr_group_id: attr_group_list[i].attr_group_id,
            attr_group_name: attr_group_list[i].attr_group_name,
            attr_id: attr.attr_id,
            attr_name: attr.attr_name,
          });
        }
      }
    }
    // 限购判断 by--lili
    let goods = _this.data.goods;
    if (goods.limit_count > 0) {
      let able_num =
        goods.limit_count -
        goods.user_order_count.cart -
        goods.user_order_count.order;
      if (_this.data.form.number > able_num) {
        wx.showToast({
          title: "当前最大购买数量为" + able_num,
          icon: "none",
        });
        return;
      }
    }
    if (type === "ADD_CART") {
      wx.showLoading({
        title: "正在提交",
        mask: true,
      });
      app.ws_micro_shoprequest({
        url: api.cart.add_cart,
        method: "POST",
        data: {
          goods_id: _this.data.id,
          attr: JSON.stringify(checked_attr_list),
          num: _this.data.form.number,
        },
        success: function (res) {
          wx.showToast({
            title: res.msg,
            icon: Number(res.code) === 0 ? "success" : "none",
          });
          wx.hideLoading();
          _this.setData({
            show_attr_picker: Number(res.code) === 1,
          });
          app.resetPurchasedNum();
        },
      });
    }
    if (type === "BUY_NOW") {
      _this.setData({
        show_attr_picker: false,
      });
      wx.navigateTo({
        url:
          "/ws_micro_shop/pages/order-submit/order-submit?goods_info=" +
          JSON.stringify({
            goods_id: _this.data.id,
            attr: checked_attr_list,
            num: _this.data.form.number,
          }),
      });
    }
  },
  attrClick(e) {
    let _this = this;
    let attr_group_id = Number(e.currentTarget.dataset.groupId);
    let attr_id = Number(e.target.dataset.id);
    let attr_group_list = _this.data.attr_group_list;
    for (let i in attr_group_list) {
      if (Number(attr_group_list[i].attr_group_id) !== attr_group_id) {
        continue;
      }
      for (let j in attr_group_list[i].attr_list) {
        if (Number(attr_group_list[i].attr_list[j].attr_id) === attr_id) {
          attr_group_list[i].attr_list[j].checked = true;
        } else {
          attr_group_list[i].attr_list[j].checked = false;
        }
      }
    }
    _this.setData({
      attr_group_list,
    });
    let check_attr_list = [];
    let check_all = true;
    for (let i in attr_group_list) {
      if (Object.prototype.hasOwnProperty.call(attr_group_list, i)) {
        let group_checked = false;
        for (let j in attr_group_list[i].attr_list) {
          if (attr_group_list[i].attr_list[j].checked) {
            check_attr_list.push(attr_group_list[i].attr_list[j].attr_id);
            group_checked = true;
            break;
          }
        }
        if (!group_checked) {
          check_all = false;
          break;
        }
      }
    }
    if (!check_all) {
      return;
    }
    wx.showLoading({
      title: "正在加载",
      mask: true,
    });
    app.ws_micro_shoprequest({
      url: api.default.goods_attr_info,
      data: {
        goods_id: _this.data.id,
        attr_list: JSON.stringify(check_attr_list),
      },
      success: function (res) {
        wx.hideLoading();
        if (res.code === 0) {
          _this.setData({
            "goods.attr_pic": res.data.pic,
            "goods.original_price": res.data.origin_price,
            "goods.oriprice": res.data.oriprice ? res.data.oriprice : 0,
            "goods.price": res.data.price,
            "goods.num": res.data.num,
            "goods.limit_count": res.data.limit_count,
            "goods.min_num": Number(res.data.min_num),
            "goods.user_order_count": res.data.user_order_count,
          });
        }
      },
    });
  },
  chooseStore() {
    // wx.removeStorageSync('latestShopId');
    let { isPlatShow } = this.data;
    if (isPlatShow) {
      app.ws_micro_shop_globalData.shopid = 0;
      wx.reLaunch({
        url: "/ws_micro_shop/pages/home/index?visit_platform=1",
      });
    } else {
      let shop = this.data.shop;
      app.util.navigateTo("/ws_micro_shop/pages/shop/shop", {
        shopinfo: JSON.stringify(shop),
      });
    }
  },
  openMap() {
    let latitude = Number(this.data.shop.latitude);
    let longitude = Number(this.data.shop.longitude);
    wx.openLocation({
      latitude,
      longitude,
      name: this.data.shop.name,
      address: this.data.shop.address,
      scale: 18,
    });
  },
  bindMember() {
    // app.ws_micro_shoprequest({
    //   url: api.default.bindmember,
    //   success: res => {
    //     if (res.code === 0) {
    //       if (res.data && res.data.access_token) {
    //         wx.setStorageSync('access_token', res.data.access_token);
    //       }
    //     }
    //   },
    // });
  },
  tabMiniCard(e) {
    let args = e.detail;
    let currentPath = "";
    let pages = getCurrentPages();
    pages.length > 0 && (currentPath = "/" + pages.pop().route);
    currentPath !== args.path &&
      setTimeout(() => {
        app.util.navigateTo(args.path, args.query);
      }, 500);
  },
  showShopQRCode() {
    let that = this;
    app.ws_micro_shoprequest({
      url: api.default.shopqrcode,
      success: (res) => {
        if (res.code === 0) {
          that.setData({
            QRcodeUrl: res.data,
            showQRcode: true,
          });
        } else {
          wx.showToast({
            title: "获取店铺二维码失败",
            icon: "none",
          });
        }
      },
    });
  },
  hideShopQRCode() {
    this.setData({
      showQRcode: false,
      QRcodeUrl: "",
    });
  },
  catchTap() {
    // it`s necessary
  },
  downloadQRcode() {
    let _this = this;
    if (!wx.saveImageToPhotosAlbum) {
      wx.showModal({
        title: "提示",
        content:
          "当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。",
        showCancel: false,
      });
      return;
    }
    wx.getSetting({
      success(res) {
        if (typeof res.authSetting["scope.writePhotosAlbum"] === "undefined") {
          _this.downLoadGoodsImg();
        } else if (res.authSetting["scope.writePhotosAlbum"] === false) {
          _this.setData({
            open_setting: true,
          });
        } else {
          _this.downLoadGoodsImg();
        }
      },
    });
  },
  downLoadGoodsImg() {
    let _this = this;
    wx.showLoading({
      title: "正在下载图片",
      mask: true,
    });
    wx.downloadFile({
      url: _this.data.QRcodeUrl,
      success: function (e) {
        wx.showLoading({
          title: "正在保存图片",
          mask: true,
        });
        wx.saveImageToPhotosAlbum({
          filePath: e.tempFilePath,
          success: function () {
            wx.showModal({
              title: "提示",
              content: "图片保存成功",
              showCancel: false,
            });
          },
          fail: function (e) {
            wx.showModal({
              title: "提示",
              content: "图片保存失败",
              showCancel: false,
            });
          },
          complete: function (e) {
            wx.hideLoading();
          },
        });
      },
      fail: function (e) {
        wx.showModal({
          title: "图片下载失败",
          content: e.errMsg + ";" + _this.data.QRcodeUrl,
          showCancel: false,
        });
      },
      complete: function (e) {
        wx.hideLoading();
      },
    });
  },
  hidebirthday() {
    this.setData({
      is_birthday: 0,
    });
  },
  getFloatIcon() {
    let that = this;
    let iconeLen = 1;
    let {
      dial,
      dial_pic,
      contact_tel,
      web_service,
      web_service_url,
      show_customer_service,
      serviceMessageTitle,
      serviceMessagePath,
      service,
      show_qywxcustomer_service,
      show_qywxcustomer_pic,
      card_openid,
      card_toopenid,
      card_id,
    } = that.data;

    let floatItems = [
      {
        type: 1, // 客服电话
        show: dial == 1,
        icon: dial_pic,
        tel: contact_tel,
      },
      {
        type: 6, // 企业客服
        show: show_qywxcustomer_service == 1,
        icon: show_qywxcustomer_pic,
      },
      {
        type: 3, // webview跳转
        show: web_service,
        icon: web_service,
        url: web_service_url,
      },
    ];
    let customerlist;
    if (Number(show_customer_service) === 1) {
      customerlist = [
        {
          type: 4, // 客服跳转
          show: true,
          icon: service,
          sessionFormStr: JSON.stringify({
            shop_id: app.ws_micro_shop_globalData.shopid,
          }),
          serviceMessageTitle: serviceMessageTitle,
          serviceMessagePath: serviceMessagePath,
        },
      ];
    } else if (
      Number(show_customer_service) === 2 ||
      Number(show_customer_service) === 3
    ) {
      customerlist = [
        {
          type: 7, // 内部跳转
          show: true,
          icon: service,
          url:
            "/common/component/universal-card/pages/message?openid=" +
            card_openid +
            "&to_openid=" +
            card_toopenid +
            "&cardid=" +
            card_id +
            "&scene=inner&m_id=0",
        },
      ];
    }
    customerlist && (floatItems = floatItems.concat(customerlist));

    for (let i = 0; i < floatItems.length; i++) {
      if (floatItems[i].show) {
        iconeLen = iconeLen + 1;
      }
    }

    that.setData({
      iconeLen,
      floatItems,
    });
  },
  onReachBottom() {
    this.getRecommendGoods();
  },
  getRecommendGoods() {
    let that = this;
    let { page, more, recommend_goods } = that.data;
    if (more) {
      wx.showLoading({
        title: "加载中...",
      });
      app.ws_micro_shoprequest({
        url: api.default.index_new,
        data: {
          type: "goods_list_single",
          page,
        },
        success: (res) => {
          wx.hideLoading();
          wx.stopPullDownRefresh();
          if (res.code === 0) {
            let list = res.data.recommend_goods;
            if (list && list.length > 0) {
              page += 1;
              that.setData({
                recommend_goods: recommend_goods.concat(list),
                page,
              });
            } else {
              // wx.showToast({
              //   title: '没有更多商品了',
              // });
              that.setData({
                more: false,
                is_show_line: true,
              });
            }
          }
        },
      });
    }
  },
  swiperChange(e) {
    this.setData({
      swiperCurrent: e.detail.current,
    });
  },
  goback() {
    wx.removeStorageSync("latestShopId");
    app.ws_micro_shop_globalData.shopid = 0;
    wx.reLaunch({
      url: "/ws_micro_shop/pages/home/index?visit_platform=1",
    });
  },
});
